package com.xja.controller;

import cn.hutool.crypto.SecureUtil;
import com.xja.exception.CustomException;
import com.xja.model.dto.EmployeeLoginDTO;
import com.xja.model.dto.EmployeeRegisterDTO;
import com.xja.model.entity.Employee;
import com.xja.model.vo.resp.EmployeeLoginVO;
import com.xja.model.vo.resp.Result;
import com.xja.service.IEmployeeService;
import com.xja.utils.UserContext;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author caijg
 * @since 2025-06-10
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Tag(name = "员工管理")
@RequiredArgsConstructor
public class AdminEmployeeController {

    private final IEmployeeService employeeService;

    @PostMapping("/login")
    @Operation(summary = "员工登录")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);
        EmployeeLoginVO employeeLoginVO = employeeService.login(employeeLoginDTO);
        return Result.success(employeeLoginVO);
    }

    @PostMapping("/sendSmsCode")
    @Operation(summary = "发送短信验证码")
    public Result<Void> sendSmsCode(@RequestBody Map<String, String> data) {
        log.info("发送短信验证码：{}", data);
        String phone = data.get("phone");
        employeeService.sendSmsCode(phone);
        return Result.success();
    }

    @PostMapping("/loginByPhone")
    @Operation(summary = "手机号登录")
    public Result<EmployeeLoginVO> loginByPhone(@RequestBody Map<String, String> data) {
        log.info("手机号登录：{}", data);
        String phone = data.get("phone");
        String code = data.get("code");
        EmployeeLoginVO employeeLoginVO = employeeService.loginByPhone(phone, code);
        return Result.success(employeeLoginVO);
    }

    @GetMapping("/info")
    @Operation(summary = "获取某个员工详细信息")
    public Result<Employee> info() {
        log.info("获取员工信息");
        Long uid = UserContext.getUid();
        Employee employee = employeeService.query().eq("id", uid).one();
        employee.setPassword(null);
        return Result.success(employee);
    }

    @PutMapping("/update")
    @Operation(summary = "更新员工信息")
    public Result<Void> update(@RequestBody Employee employee) {
        log.info("更新员工信息：{}", employee);
        employeeService.updateById(employee);
        return Result.success();
    }

    @PutMapping("/updatePwd")
    @Operation(summary = "更新员工密码")
    public Result<Void> updatePwd(@RequestBody Map<String, String> data) {
        // 1.获取用户id
        Long uid = UserContext.getUid();
        Employee employee = employeeService.getById(uid);
        // 2.获取旧密码和新密码
        String oldPassword = data.get("oldPassword");
        String newPassword = data.get("newPassword");

        // 3.校验旧密码是否正确
        if (!SecureUtil.md5(oldPassword).equals(employee.getPassword())) {
            throw new CustomException("密码错误", 400);
        }
        // 4.调用service更新密码
        employeeService.update()
                .eq("id", uid)
                .set("password", SecureUtil.md5(newPassword))
                .update();

        return Result.success();
    }

    @GetMapping("/list")
    @Operation(summary = "获取员工列表")
    public Result<List<Employee>> list() {
        log.info("获取员工列表");
        List<Employee> list = employeeService.list();
        // 遍历设置密码为null
        list.forEach(employee -> employee.setPassword(null));
        return Result.success(list);
    }

    @PostMapping("/add")
    @Operation(summary = "新增员工")
    public Result<Void> add(@RequestBody Employee employee) {
        log.info("新增员工：{}", employee);
        // 1.加密密码
        employee.setPassword(SecureUtil.md5(employee.getPassword()));
        // 2.设置创建时间
        employee.setCreatedTime(LocalDateTime.now());
        // 3.设置状态为启用
        employee.setStatus(1);
        // 4.保存员工
        employeeService.save(employee);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除员工")
    public Result<Void> delete(@PathVariable Long id) {
        log.info("删除员工：{}", id);
        // 不能删除超级管理员
        Employee employee = employeeService.getById(id);
        if ("超级管理员".equals(employee.getRole())) {
            return Result.error("超级管理员不能删除");
        }
        employeeService.removeById(id);
        return Result.success();
    }

    @PutMapping("/status")
    @Operation(summary = "修改员工状态")
    public Result<Void> status(@RequestBody Employee employee) {
        log.info("修改员工状态：{}", employee);
        // 不能禁用超级管理员
        Employee emp = employeeService.getById(employee.getId());
        if ("超级管理员".equals(emp.getRole()) && employee.getStatus() == 0) {
            return Result.error("超级管理员不能禁用");
        }
        employeeService.updateById(employee);
        return Result.success();
    }

    @PostMapping("/logout")
    @Operation(summary = "退出登录")
    public Result<Void> logout(HttpServletRequest request) {
        log.info("员工退出登录, id={}", UserContext.getUid());
        employeeService.logout(request);
        return Result.success();
    }
}